package com.dopplr.examples
{
    import com.dopplr.api.API;
    import com.dopplr.api.Traveller;
    import com.dopplr.api.Trip;
    
    import flash.display.LoaderInfo;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.ErrorEvent;
    import flash.events.StatusEvent;

    /** An example that grabs the authenticated user and then grabs their fellow travellers and their home cities.
     *  It then loops through the list of fellow travellers and draws a square in the color of their current city. */
    [SWF(backgroundColor="#ffffff")]
    public class DopplrBasics extends Sprite
    {
        public var api:API;
        
        public function DopplrBasics()
        {
            stage.align = StageAlign.TOP_LEFT;
            stage.scaleMode = StageScaleMode.NO_SCALE;

            var token:String = LoaderInfo(root.loaderInfo).parameters.token;
            if (token) {    
                api = new API(token);

                // load the currently authenticated user
                api.loadAuthenticatedUser(gotMe);

                api.addEventListener(ErrorEvent.ERROR, onAPIError);
                api.addEventListener(StatusEvent.STATUS, onAPIStatus);
            }
            else {
                trace("problem initializing dopplr access: no token found");
            }                        
        }
        
        public function gotMe(user:Traveller):void
        {
            // do something with the user's trips?
            for each (var trip:Trip in user.trips) {
                trace("from " + trip.departure + " to " + trip.city);
                // we also have lat/lon, start/finish days, and notes
            }
            
            // try loading the user's fellow travellers instead
            // (we could have done this first, but it's a long call)
            api.loadFellowTravellers(gotEm);
        }
        
        public function gotEm(users:Array):void
        {
            // fellow travellers don't come with home or current cities, so...
            api.loadFellowTravellersInfo(users, gotHomes);
        }
        
        public function gotHomes(users:Array):void
        {
            var boxX:Number = 0;
            // do something with every fellow traveller....
            for each (var user:Traveller in users) {
                graphics.beginFill(user.homeCity.rgb);
                graphics.drawRect(boxX,0,10,10);
                boxX += 10;
            }            
        }
        
        public function onAPIError(event:ErrorEvent):void
        {
            // do something about errors here
            var errorText:String = event.text;
            trace(errorText);
        }

        public function onAPIStatus(event:StatusEvent):void
        {
            // do something about status here
            trace(event.level + ": " + event.code);
        }
        
    }
}